<template>
  <el-card class="full-card">
    <h2 class="page-title">用户管理</h2>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" label-width="100px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="用户ID">
            <el-input v-model.trim="queryParams.userId" placeholder="请输入用户ID" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户名">
            <el-input v-model.trim="queryParams.username" placeholder="请输入用户名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="真实姓名">
            <el-input v-model.trim="queryParams.realName" placeholder="请输入真实姓名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="知识等级">
            <el-select v-model="queryParams.knowledgeLevel" placeholder="请选择等级" clearable>
              <el-option label="初学者" value="0" />
              <el-option label="爱好者" value="1" />
              <el-option label="专家" value="2" />
              <el-option label="研究人员" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="search-btn-group">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%; margin: 20px 0"
        header-cell-class-name="table-header"
    >
      <el-table-column prop="userId" label="用户ID" min-width="100px" />
      <el-table-column prop="username" label="用户名" min-width="120px" />
      <el-table-column prop="realName" label="真实姓名" min-width="120px" />
      <el-table-column label="头像" min-width="80px">
        <template #default="{ row }">
          <el-image
              :src="row.avatarUrl || 'https://2023-08-02first-use-oss.oss-cn-chengdu.aliyuncs.com/1fe9fc789ec14a7e8244293e7275f750.png'"
              style="width: 40px; height: 40px; border-radius: 50%; margin: 4px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="200px" />
      <el-table-column prop="phoneNumber" label="手机号" min-width="120px" />
      <el-table-column prop="knowledgeLevel" label="知识等级" min-width="120px">
        <template #default="{ row }">
          <el-tag :type="getLevelTag(row.knowledgeLevel)">
            {{ getLevelLabel(row.knowledgeLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isUser" label="角色" min-width="100px">
        <template #default="{ row }">
          <el-tag
              :type="row.originalRole === '1' ? 'success' : 'info'"
              effect="dark"
              size="small"
          >
            {{ row.originalRole === '1' ? '管理员' : '用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120px">
        <template #default="{ row }">
          <el-switch
              v-model="row.currentRole"
              :active-value="'1'"
              :inactive-value="'0'"
              @change="handleRoleChange(row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :loading="row.isLoading"
              :disabled="row.isUpdating"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="fetchData"
        class="pagination"
    />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import adminApi from "@/apis/adminApi";

// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 10,
  userId: null,
  username: '',
  realName: '',
  knowledgeLevel: '',
  isUser: ''
});

// 表格数据
const tableData = ref([]);
const total = ref(0);

// 知识等级转换
const getLevelLabel = (level) => {
  if (level === null) return '未知';
  const levels = ['初学者', '爱好者', '专家', '研究人员'];
  return levels[level] || '未知';
};

const getLevelTag = (level) => {
  if (level === null) return 'info'; // 默认类型
  const tags = ['info', 'success', 'warning', 'danger'];
  return tags[level] || 'info';
};

// 获取数据
const fetchData = async () => {
  try {
    const res = await adminApi.getUserRoleList(queryParams.value);
    if (res.code === 200) {
      tableData.value = res.data.records.map(item => ({
        ...item,
        originalRole: item.isUser.toString(),
        currentRole: item.isUser.toString(),
        isLoading: false,
        isUpdating: false
      }));
      total.value = res.data.total;
    }
  } catch (error) {
    ElMessage.error('数据加载失败');
  }
};

// 处理查询
const handleSearch = () => {
  queryParams.value.currentPage = 1;
  fetchData();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    currentPage: 1,
    pageSize: 10,
    userId: null,
    username: '',
    realName: '',
    knowledgeLevel: '',
    isUser: ''
  };
  fetchData();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size;
  fetchData();
};

// 处理角色切换
const handleRoleChange = async (row) => {
  if (row.isUpdating || row.originalRole === row.currentRole) return;

  row.isUpdating = true;
  row.isLoading = true;

  try {
    const res = await adminApi.updateUserRole({
      userId: row.userId,
      isUser: row.currentRole
    });
    if (res.code === 200) {
      ElMessage.success('角色更新成功');
      row.originalRole = row.currentRole;
    } else {
      throw new Error(res.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error(error.message || '操作异常');
    row.currentRole = row.originalRole;
  } finally {
    row.isLoading = false;
    row.isUpdating = false;
  }
};

// 初始化数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.full-card {
  margin: 20px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.search-form :deep(.el-form-item__content) {
  width: 100%;
}

.search-btn-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.search-btn-group .el-button {
  margin-left: 10px;
}

.table-header {
  background: #f5f7fa !important;
  font-weight: 600;
}

.pagination {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-switch) {
  transform: scale(0.9);
}

/* 头像样式优化 */
:deep(.el-table .avatar-column) {
  padding: 0 !important;
}

:deep(.el-image) {
  display: inline-block;
  margin: auto;
}

:deep(.el-image img) {
  object-fit: cover;
  border-radius: 50%;
}

/* 确保图片在单元格中居中 */
:deep(.el-table__cell .el-image) {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
